package listen

import (
	"github.com/gookit/event"
	"github.com/nfnt/resize"
	"github.com/vueadmin/app/admin/model"
	"github.com/vueadmin/global"
	"github.com/vueadmin/utils/conv"
	"image"
	"image/jpeg"
	"image/png"
	"net/url"
	"os"
)

// 图片生成缩略图
func ThumbImg(e event.Event) error {
	if conv.Int(e.Data()["upload_config_id"]) == 0 || global.CONF.Disks != "local" {
		return nil
	}
	u, _ := url.Parse(e.Data()["filepath"].(string))
	filename := u.Path
	file, err := os.Open(global.CONF.AccessPath + filename)
	if err != nil {
		global.LOG.Error("生成缩略图错误:", err)
	}
	defer file.Close()
	img, format, err := image.Decode(file)
	if err != nil {
		global.LOG.Error("生成缩略图错误:", err)
	}
	var info model.AdminUploadconfig
	global.DB.Where("id", conv.Int(e.Data()["upload_config_id"])).First(&info)

	var thumbnail image.Image
	switch info.ThumbType {
	case 1:
		thumbnail = resize.Thumbnail(conv.Uint(info.ThumbWidth), conv.Uint(info.ThumbHeight), img, resize.Lanczos3)
	case 6:
		thumbnail = resize.Resize(conv.Uint(info.ThumbWidth), conv.Uint(info.ThumbHeight), img, resize.Lanczos3)
	}

	out, err := os.Create(global.CONF.AccessPath + filename)
	if err != nil {
		global.LOG.Error("生成缩略图错误:", err)
	}
	defer out.Close()

	switch format {
	case "jpeg":
		jpeg.Encode(out, thumbnail, nil)
	case "png":
		png.Encode(out, thumbnail)
	default:
		global.LOG.Error("当前格式不支持生成缩略图:", format)
	}

	return nil
}
